package net.huashitong.Indicators.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.web.model.Ztree;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.dao.AppMessageDao;
import net.huashitong.Indicators.dao.AppMsgGroupDao;
import net.huashitong.Indicators.dataBean.UserAndDeptDataBean;
import net.huashitong.Indicators.entity.AppMessage;
import net.huashitong.Indicators.entity.AppMsgGroup;
import net.huashitong.Indicators.filter.AppMessageFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.Collator;
import java.util.*;

import static net.huashitong.Indicators.utils.CodeUtils.findStrNum;

@Service
public class AppMessageService extends StringPKService<AppMessage> {

    @Autowired
    private AppMessageDao dao;
    @Autowired
    private AppMsgGroupDao msgGroupDao;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysTableService tableService;

    @Override
    protected BaseDao<AppMessage, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(AppMessage obj) {
        obj.setSysId(tableService.updateMaxSysId("app_message", null));
    }


    public List<Map<String, Object>> getTree(List<Ztree> trees) {
        List<Map<String, Object>> oneList = new ArrayList<>();
        List<Map<String, Object>> twoList = new ArrayList<>();
        List<Map<String, Object>> threeList = new ArrayList<>();
//        List<Map<String, Object>> fourList = new ArrayList<>();

        List<UserAndDeptDataBean> userAndDept = dao.queryAllUserAndDept();
        for (Ztree tree : trees) {
            if (findStrNum(tree.getpId(), "/") == 1) {
                //一级部门
                Map<String, Object> oneMap = new HashMap<>();
                oneMap.put("name", tree.getName());
                String[] ids = tree.getId().split("/");
                String id = ids[1];
                oneMap.put("id", id);
                oneMap.put("pid", "");
                oneList.add(oneMap);
            }
            if (findStrNum(tree.getpId(), "/") == 2) {
                //二级部门
                Map<String, Object> twoMap = new HashMap<>();
                twoMap.put("name", tree.getName());
                String[] ids = tree.getId().split("/");
                String pid = ids[1];
                String id = ids[2];
                twoMap.put("id", id);
                twoMap.put("pid", pid);
                twoList.add(twoMap);
            }
            if (findStrNum(tree.getpId(), "/") == 3) {
                //三级部门
                Map<String, Object> threeMap = new HashMap<>();
                threeMap.put("name", tree.getName());
                String[] ids = tree.getId().split("/");
                String pid = ids[2];
                String id = ids[3];
                threeMap.put("id", id);
                threeMap.put("pid", pid);
                threeList.add(threeMap);
            }
//            if (findStrNum(tree.getpId(), "/") == 4) {
//                //四级部门
//                Map<String, Object> fourMap = new HashMap<>();
//                fourMap.put("name", tree.getName());
//                String[] ids = tree.getId().split("/");
//                String pid = ids[3];
//                String id = ids[4];
//                fourMap.put("id", id);
//                fourMap.put("pid", pid);
//                fourList.add(fourMap);
//            }
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> oneDept : oneList) {
            List<Map<String, Object>> result2 = new ArrayList<>();
            for (UserAndDeptDataBean u : userAndDept) {
                if (oneDept.get("id").equals(u.getDeptId())) {
                    Map<String, Object> userMap = new HashMap<>();
                    userMap.put("id", u.getUserId());
                    userMap.put("name", u.getName());
                    userMap.put("userName", u.getUserName());
                    userMap.put("tel", u.getMobile());
                    userMap.put("child", new ArrayList<>());
                    result2.add(userMap);
                }
            }
            //用户按名字排序
            Collections.sort(result2, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if (ObjectUtils.isBlank(o1.get("name")) || ObjectUtils.isBlank(o2.get("name"))) {
                        return -1;
                    } else {
                        if (StringUtils.isBlank(o1.get("name").toString()) || StringUtils.isBlank(o2.get("name").toString())) {
                            return -1;
                        }
                    }
                    //注意:按照中文拼音排序要进行下面的设置
                    Comparator<Object> com = Collator.getInstance(Locale.CHINA);
                    return ((Collator) com).compare(o1.get("name").toString(), o2.get("name").toString());
                }
            });
            for (Map<String, Object> twoDept : twoList) {
                List<Map<String, Object>> result3 = new ArrayList<>();
                for (UserAndDeptDataBean u : userAndDept) {
                    if (twoDept.get("id").equals(u.getDeptId())) {
                        Map<String, Object> userMap = new HashMap<>();
                        userMap.put("id", u.getUserId());
                        userMap.put("name", u.getName());
                        userMap.put("userName", u.getUserName());
                        userMap.put("tel", u.getMobile());
                        userMap.put("child", new ArrayList<>());
                        result3.add(userMap);
                    }
                }
                //用户按名字排序
                Collections.sort(result3, new Comparator<Map<String, Object>>() {
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        if (ObjectUtils.isBlank(o1.get("name")) || ObjectUtils.isBlank(o2.get("name"))) {
                            return -1;
                        } else {
                            if (StringUtils.isBlank(o1.get("name").toString()) || StringUtils.isBlank(o2.get("name").toString())) {
                                return -1;
                            }
                        }
                        //注意:按照中文拼音排序要进行下面的设置
                        Comparator<Object> com = Collator.getInstance(Locale.CHINA);
                        return ((Collator) com).compare(o1.get("name").toString(), o2.get("name").toString());
                    }
                });

//                if (result3.size() > 0) {
//                    if (oneDept.get("id").equals(twoDept.get("pid"))) {
//                        twoDept.put("child", result3);
//                        result2.add(twoDept);
//                    }
//                }

                for (Map<String, Object> threeDept : threeList) {
                    List<Map<String, Object>> result4 = new ArrayList<>();
                    for (UserAndDeptDataBean u : userAndDept) {
                        if (threeDept.get("id").equals(u.getDeptId())) {
                            Map<String, Object> userMap = new HashMap<>();
                            userMap.put("id", u.getUserId());
                            userMap.put("name", u.getName());
                            userMap.put("userName", u.getUserName());
                            userMap.put("tel", u.getMobile());
                            userMap.put("child", new ArrayList<>());
                            result4.add(userMap);
                        }
                    }
                    //用户按名字排序
                    Collections.sort(result4, new Comparator<Map<String, Object>>() {
                        @Override
                        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                            if (ObjectUtils.isBlank(o1.get("name")) || ObjectUtils.isBlank(o2.get("name"))) {
                                return -1;
                            } else {
                                if (StringUtils.isBlank(o1.get("name").toString()) || StringUtils.isBlank(o2.get("name").toString())) {
                                    return -1;
                                }
                            }
                            //注意:按照中文拼音排序要进行下面的设置
                            Comparator<Object> com = Collator.getInstance(Locale.CHINA);
                            return ((Collator) com).compare(o1.get("name").toString(), o2.get("name").toString());
                        }
                    });

                    if (result4.size() > 0) {
                        if ((twoDept.get("id").equals(threeDept.get("pid")))&&(oneDept.get("id").equals(twoDept.get("pid")))) {
                            threeDept.put("child", result4);
                            result3.add(threeDept);
                        }
                    }
                }
                if (result3.size() > 0) {
                    if (oneDept.get("id").equals(twoDept.get("pid"))) {
                        twoDept.put("child", result3);
                        result2.add(twoDept);
                    }
                }
            }
            oneDept.put("child", result2);
            result.add(oneDept);
        }
        return result;
    }


    public List<Map<String, Object>> queryAllMsgGroup() {
        //查询所有分组
        List<AppMsgGroup> groups = msgGroupDao.queryByOrderCreateDate();
        List<Map<String, Object>> result = this.dealWithMsgGroup(groups);
        return result;
    }

    /**
     * 查询所有分组信息
     */
    public List<Map<String, Object>> dealWithMsgGroup(List<AppMsgGroup> groups) {
        //查询所有用户带部门信息
        Map<String, UserAndDeptDataBean> userAndDeptMap = queryAllUserDept();

        List<Map<String, Object>> result = new ArrayList<>();
        for (AppMsgGroup g : groups) {
            Map<String, Object> oneMap = new TreeMap<>();
            oneMap.put("groupName", g.getGroupName());
            oneMap.put("groupSysId", g.getSysId());
            String userIds = g.getUserIds();
            String[] userArr = userIds.split(";");
            List<String> userIdsList = Arrays.asList(userArr);
            List<Map<String, String>> users = new ArrayList();
            for (String userId : userIdsList) {
                UserAndDeptDataBean userAndDeptDataBean = userAndDeptMap.get(userId);
                if (ObjectUtils.isNotBlank(userAndDeptDataBean)) {
                    Map<String, String> map = new HashMap<>();
                    map.put("userName", userAndDeptDataBean.getName());
                    map.put("userId", userAndDeptDataBean.getUserId());
                    map.put("deptName", userAndDeptDataBean.getDeptName());
                    map.put("deptId", userAndDeptDataBean.getDeptId());
                    map.put("tel", userAndDeptDataBean.getMobile());
                    users.add(map);
                }
            }
            oneMap.put("userList", users);
            result.add(oneMap);
        }
        return result;
    }


    /**
     * 查询所有分组信息2（拼接到联系人）
     */
    public List<Map<String, Object>> queryWithMsgGroup2(List<AppMsgGroup> groups) {

        //查询所有用户带部门信息
        Map<String, UserAndDeptDataBean> userAndDeptMap = this.queryAllUserDept();

        List<Map<String, Object>> result = new ArrayList<>();
        for (AppMsgGroup g : groups) {
            Map<String, Object> oneMap = new TreeMap<>();
            oneMap.put("pid", "group");
            oneMap.put("name", g.getGroupName());
            oneMap.put("id", g.getSysId());
            String userIds = g.getUserIds();
            String[] userArr = userIds.split(",");
            List<String> userIdsList = Arrays.asList(userArr);
            List<Map<String, Object>> users = new ArrayList();
            for (String userId : userIdsList) {
                UserAndDeptDataBean userAndDeptDataBean = userAndDeptMap.get(userId);
                if (ObjectUtils.isNotBlank(userAndDeptDataBean)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", userAndDeptDataBean.getUserId());
                    map.put("tel", userAndDeptDataBean.getMobile());
                    map.put("name", userAndDeptDataBean.getName());
                    map.put("userName", userAndDeptDataBean.getDeptName());
                    map.put("child", new ArrayList<>());
                    users.add(map);
                }
            }
            if(!("局领导".equals(g.getGroupName())||"管理员".equals(g.getGroupName()))){
                //用户按名字排序
                Collections.sort(users, new Comparator<Map<String, Object>>() {
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        if (StringUtils.isBlank(o1.get("name").toString()) || StringUtils.isBlank(o2.get("name").toString())) {
                            return -1;
                        }
                        //注意:按照中文拼音排序要进行下面的设置
                        Comparator<Object> com = Collator.getInstance(Locale.CHINA);
                        return ((Collator) com).compare(o1.get("name"), o2.get("name"));
                    }
                });
            }
            oneMap.put("child", users);
            result.add(oneMap);
        }
        return result;
    }


    public Map<String, UserAndDeptDataBean> queryAllUserDept() {
        //查询所有用户带部门信息
        List<UserAndDeptDataBean> userAndDept = dao.queryAllUserAndDept();
        Map<String, UserAndDeptDataBean> userAndDeptMap = new HashMap<>();
        for (UserAndDeptDataBean bean : userAndDept) {
            if (!userAndDeptMap.containsKey(bean.getUserId())) {
                userAndDeptMap.put(bean.getUserId(), bean);
            }
        }
        return userAndDeptMap;
    }

    public boolean addSendMsg(List<String> userIds, AppMessageFilter filter,List<String> shortUserIds) {
        List<String> needUserIds = new ArrayList<>();
        //查询所有用户带部门信息
        List<UserAndDeptDataBean> userAndDept = dao.queryAllUserAndDept();
        Map<String, UserAndDeptDataBean> userAndDeptMap = new HashMap<>();
        for (UserAndDeptDataBean bean : userAndDept) {
            if (!userAndDeptMap.containsKey(bean.getUserId())) {
                userAndDeptMap.put(bean.getUserId(), bean);
            }
        }
        //手机号码
        List<String> tels = new ArrayList<>();
        List<AppMessage> appMessages = new ArrayList<>();
        List<String> usersUnique = new ArrayList<>();
        //set集合去重，不改变原有的顺序
        Set set = new HashSet();
        for (String str : userIds) {
            if (set.add(str)) {
                usersUnique.add(str);
            }
        }
        needUserIds.addAll(usersUnique);
        needUserIds.add(filter.getSender());        //发送的时候也发送自己本身
        for (String userId : needUserIds) {
            AppMessage appMessage = new AppMessage();
            appMessage.setMsgText(filter.getMsgText());         //内容
            appMessage.setMsgTitle(filter.getMsgTitle());       //标题
            appMessage.setReadStatus("0");                      //每条消息初始化：未读
            appMessage.setSender(filter.getSender());           //发送方
            appMessage.setReceiver(userId);                     //接收方
            appMessage.setSource(filter.getSource());           //消息来源
            appMessage.setIfSMS(filter.isIfSMS());              //接收短信标志（1/0）
            appMessage.setPicture(filter.getPicture());
            appMessages.add(appMessage);
        }
        this.batchSave(appMessages);

        //查询发送消息当中有手机号码的用户，并将手机号码提取出来
        for(String shortUser : shortUserIds){
            UserAndDeptDataBean bean = userAndDeptMap.get(shortUser);
            if (ObjectUtils.isNotBlank(bean)) {
                if (StringUtils.isNotBlank(bean.getMobile())) {
                    tels.add(bean.getMobile());
                }
            }
        }
        //接收短信用户
        List<String> shortsTelUnique = new ArrayList<>();
        //set集合去重，不改变原有的顺序
        Set shortSet = new HashSet();
        for (String str : tels) {
            if (shortSet.add(str)) {
                shortsTelUnique.add(str);
            }
        }

        //发送消息完之后再发送短信
        if (filter.isIfSMS()) {
            for (String tel : shortsTelUnique) {
                System.out.println(tel + "接收短信中。。。。。。。。。。。。。。");
                SmsProcess sms = new SmsProcess();
                String smsContent = "您有一条《厦门数据APP》的最新消息，请登录APP进行查看！";
                Map<String, Object> map = sms.SendMts(tel, smsContent);
            }
        }
        return true;
    }

    public List<AppMessage> queryByUserIdOrderCreateDate(AppMessageFilter filter) {
        return dao.queryByUserIdOrderCreateDate(filter);
    }
}
